package com.fengmoxi.ctv.manage;

import static android.content.Context.RECEIVER_EXPORTED;
import static android.os.Build.VERSION.SDK_INT;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;

public class HomeButtonReceiver {
    private static final String TAG = HomeButtonReceiver.class.getSimpleName();
    private final Context mContext;
    private final IntentFilter mHomeBtnIntentFilter;
    private final OnHomeBtnPressListener mOnHomeBtnPressListener;
    private final receiver mHomeBtnReceiver;

    public HomeButtonReceiver(Context context, OnHomeBtnPressListener onHomeBtnPressListener) {
        mContext = context;
        mHomeBtnReceiver = new receiver();
        mHomeBtnIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        mOnHomeBtnPressListener = onHomeBtnPressListener;
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public void start() {
        if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            mContext.registerReceiver(mHomeBtnReceiver, mHomeBtnIntentFilter, RECEIVER_EXPORTED);
        } else {
            mContext.registerReceiver(mHomeBtnReceiver, mHomeBtnIntentFilter);
        }
    }

    public void stop() {
        mContext.unregisterReceiver(mHomeBtnReceiver);
    }

    public interface OnHomeBtnPressListener {
        void onHomeBtnPress();

        void onHomeBtnLongPress();
    }

    private void receive(Intent intent) {
        String action = intent.getAction();
        if (action != null && action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra("reason");
            if (reason != null) {
                if (null != mOnHomeBtnPressListener) {
                    if (reason.equals("homekey")) {
                        // 按Home按键
                        Log.i(TAG, "homekey");
                        mOnHomeBtnPressListener.onHomeBtnPress();
                    } else if (reason.equals("recentapps")) {
                        // 长按Home按键
                        Log.i(TAG, "recentapps");
                        mOnHomeBtnPressListener.onHomeBtnLongPress();
                    }
                }
            }
        }
    }

    class receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            receive(intent);
        }
    }
}
